package edu.gatech.cs2340.sharks.fms;

/**
 * EditItemActivity.java
 * @author Steven Mitchell
 * 
 * This activity allows users to edit items in the database.
 * If the item does not belong to the user, the database will give an error upon submitting changes.
 * Otherwise, user returns to the view item activity.
 */

import java.util.List;
import edu.gatech.cs2340.sharks.fms.data.*;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class EditItemActivity extends Activity
{	
	/**
	 * The item being edited
	 */
	private Item item;
	
	/**
	 * The lost or found status of the item being edited
	 */
	private Item.Status itemStatus;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_edit_item);

		//gets the current intent and its extras
		Intent intent = getIntent();
		Bundle extras = intent.getExtras(); 
		
		//obtains the itemID and instantiates the item variable
		int itemID = extras.getInt("ItemID");
		Packet<Item> current = DBMgr.getItem(itemID);
		item = current.value;
		
		//gets text field objects from the layout
		EditText nameField = (EditText) findViewById(R.id.editItemName);
		EditText yearField = (EditText) findViewById(R.id.year);
		EditText monthField = (EditText) findViewById(R.id.month);
		EditText dayField = (EditText) findViewById(R.id.day);
		EditText locationField = (EditText) findViewById(R.id.editLocationLost);
		EditText descField = (EditText) findViewById(R.id.editItemDescription);
		EditText rewardField = (EditText) findViewById(R.id.editReward);
		
		//splits the item's date
		String[] date = item.date.split("-");
		
		//sets all of the textfields
		nameField.setText(item.name);
		yearField.setText(date[0]);
		monthField.setText(date[1]);
		dayField.setText(date[2]);
		locationField.setText(item.location);
		descField.setText(item.description);
		rewardField.setText(String.valueOf(item.reward));
		
		//sets the item status
		itemStatus = item.status;
		
		//checks the "lost" or "found" radio button, depending on the item status
		RadioButton lostButton = (RadioButton) findViewById(R.id.editLost);
		RadioButton foundButton = (RadioButton) findViewById(R.id.editFound);
		
		if (itemStatus == Item.Status.LOST) lostButton.setChecked(true);
		else foundButton.setChecked(true);
	}

	/**
	 * Queries the database for the list of possible tags and
	 * concatenates them into a string. Afterward, it adds the
	 * string to a dialog that is displayed to the user.
	 * 
	 * @param view The button that runs the method when clicked.
	 */
	public void displayTags(View view)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		String tagString = "";
		Packet<List<Tag>> tagList = DBMgr.allTags();

		for (Tag t : tagList.value)
		{
			if ("".equals(tagString)) tagString += t.name;
			else tagString += ", " + t.name;
		}
		
		builder.setMessage("Here are the tags you may use: \n" + tagString);
		builder.setPositiveButton("Close", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int id) { }
		});
		
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	/**
	 * Sets lost to true or false based on which radio button the user has selected
	 * 
	 * @param view The button that is checked.
	 */
	public void setLostOrFound(View view)
	{
		boolean checked = ((RadioButton) view).isChecked();
		switch(view.getId())
		{
			case R.id.editLost:
			    if (checked) itemStatus = Item.Status.LOST;
			    break;
			case R.id.editFound:
			    if (checked) itemStatus = Item.Status.FOUND;
			    break;
		}
	}

	/**
	 * Updates the item data in the database. Obtains all user input from text fields,
	 * re-creates the item object, and overrites the old item in the database.
	 * If the item editing fails, then an error message is retuned.
	 * If the date input follows the incorrect format, an error message is returned.
	 * Else, the activity finishes and the user returns to the view item page.
	 * 
	 * @param view The button clicked that starts this method.
	 */
	public void update(View view)
	{	
		EditText nameField = (EditText) findViewById(R.id.editItemName);
		EditText yearField = (EditText) findViewById(R.id.year);
		EditText monthField = (EditText) findViewById(R.id.month);
		EditText dayField = (EditText) findViewById(R.id.day);
		EditText locationField = (EditText) findViewById(R.id.editLocationLost);
		EditText descField = (EditText) findViewById(R.id.editItemDescription);
		EditText rewardField = (EditText) findViewById(R.id.editReward);
		
		String newName = nameField.getText().toString();
		String newYear = yearField.getText().toString();
		String newMonth = monthField.getText().toString();
		String newDay = dayField.getText().toString();
		String newLoc = locationField.getText().toString();
		String newDesc = descField.getText().toString();
		String newRewText = rewardField.getText().toString();
		int newRew = Integer.parseInt(newRewText);
		
		//combines year, month, and day
		String newDate = newYear + "-" + newMonth + "-" + newDay;
		
		item.name = newName;
		item.date = newDate;
		item.location = newLoc;
		item.description = newDesc;
		item.reward = newRew;
		item.status = itemStatus;
		
		Status status = DBMgr.editItem(DBMgr.user, item);
		final TextView statusField = (TextView) findViewById(R.id.statusText);
		
		if (status == null) statusField.setText("Null status encountered!");
		else if (status.code() == Status.Code.OK)
		{
			Intent nextIntent = new Intent(this, ViewItemActivity.class);
			nextIntent.putExtra("ItemID", item.id()); 
			startActivity(nextIntent);
			finish();
		}
		else if (newDate.length() != 10) statusField.setText("Please use the correct date format! mm/dd/yyyy" + newDate);
		else statusField.setText(status.toString());
	}
	
	/**
	 * Deletes the item from the database.
	 * If successful, activity finishes and user is returned to the home screen.
	 * Else, an error message is displayed.
	 * 
	 * @param view The button clicked that starts this method.
	 */
	public void delete(View view)
	{	
		Status status = DBMgr.deleteItem(DBMgr.user, item);
		if (status.code() == Status.Code.OK)
		{
			Intent nextIntent = new Intent(this, HomeActivity.class);
			startActivity(nextIntent);
			finish();
		}
		else
		{
			final TextView statusField = (TextView) findViewById(R.id.statusText);
			statusField.setText(status.toString());
		}
	}
	
	/**
	 * Finishes the activity and returns the user to the view item activity.
	 * 
	 * @param view The button clicked that starts the activity
	 */
	public void cancel(View view)
	{
		finish();
	}
}

